package com.yangtu.nearbyshop.db.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangtu.nearbyshop.db.dao.NearbyshopDispatchMapper;
import com.yangtu.nearbyshop.db.dao.NearbyshopPurchaseMapper;
import com.yangtu.nearbyshop.db.domain.NearbyshopPurchase;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopPurchaseService;
import com.yangtu.nearbyshop.db.vo.NearbyshopPurchaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 采购表 服务实现类
 * </p>
 *
 * @author wanglei
 * @since 2019-08-27
 */
@Service
public class NearbyshopPurchaseServiceImpl extends ServiceImpl<NearbyshopPurchaseMapper, NearbyshopPurchase> implements INearbyshopPurchaseService {

    @Autowired
    NearbyshopPurchaseMapper purchaseMapper;

    @Autowired
    NearbyshopDispatchMapper dispatchMapper;

    @Override
    public IPage<NearbyshopPurchase> selectByPage(Page<NearbyshopPurchase> page, Integer purchaseStatus,String purchaseNo) {
        // 不进行 count sql 优化，解决 MP 无法自动优化 SQL 问题，这时候你需要自己查询 count 部分
        // page.setOptimizeCountSql(false);
        // 当 total 为小于 0 或者设置 setSearchCount(false) 分页插件不会进行 count 查询
        // 要点!! 分页返回的对象与传入的对象是同一个
        return purchaseMapper.selectByPage(page, purchaseStatus,purchaseNo);
    }

    @Override
    public IPage<NearbyshopPurchaseVo> selectOrderByPage(Page<NearbyshopPurchaseVo> page, Integer purchaseStatus) {
        return purchaseMapper.selectOrderByPage(page, purchaseStatus);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePurchaseStatus(String pno, Integer purchaseStatus) {
        purchaseMapper.updatePurchaseStatus(pno,purchaseStatus);
        List<NearbyshopPurchase> ps = purchaseMapper.selectList(new QueryWrapper<NearbyshopPurchase>()
                .eq(StringUtils.isNotEmpty(pno),"purchase_no",pno)
                .eq("purchase_status",purchaseStatus));

        List<String> pnos = new ArrayList<>();
        for(NearbyshopPurchase np: ps){
            if(!pnos.contains(np.getPurchaseNo())){
                pnos.add(np.getPurchaseNo());
                dispatchMapper.updateDispatchByPno(null,pno,1,null);
            }
        }
    }
}
